package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.base.ListNode;

public class RemoveDuplicatesFromSortedList2 {

    /**
     * 1. 如果当前元素的值出现重复，就循环删除下一个元素，直到没有重复为止，然后再删除当前元素
     * 2. 如果当前元素的值没有重复，则直接遍历下一个元素
     */
    public ListNode deleteDuplicates(ListNode head) {
        ListNode newHead = new ListNode(-1, head);
        ListNode prev = newHead, node = head;
        while (node != null){
            int val = node.val;
            if (node.next != null && node.next.val == val){
                while (node.next != null && node.next.val == val){
                    node = node.next;
                }
                prev.next = node.next;
            } else {
                prev = prev.next;
            }
            node = node.next;
        }
        return newHead.next;
    }

    public static void main(String[] args) {
        ListNode head = ListNode.build(1,2,3,3,3,4,4,5,5);
        ListNode listNode = new RemoveDuplicatesFromSortedList2().deleteDuplicates(head);
        System.out.println(listNode);
    }

}
